package com.pan.lock;

import lombok.extern.slf4j.Slf4j;

import java.util.Stack;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author by panstark
 * @description
 * @notice
 * @date 2021/4/30
 */
@Slf4j
public class ReetrantLockDemo3 {

    public static void main(String[] args) {
        /**
         * 锁对象
         */
        final Lock lock = new ReentrantLock();

        final Condition conditionList = lock.newCondition();
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                lock.lock();
                try {
                    System.out.println(Thread.currentThread().getName()+"进入等待。");
                    conditionList.await();
                    System.out.println(Thread.currentThread().getName()+"被唤醒，并开始后续业务操作。");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    System.out.println(Thread.currentThread().getName()+"解锁开始。");
                    lock.unlock();
                    System.out.println(Thread.currentThread().getName()+"解锁结束。");
                }
            }
        });
        t1.setName("等待线程");

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                lock.lock();
                try {
                    System.out.println(Thread.currentThread().getName()+"进行通知。");
                    conditionList.signal();
                    System.out.println(Thread.currentThread().getName()+"通知完成。");
                }finally {
                    System.out.println(Thread.currentThread().getName()+"进行解锁。");
                    lock.unlock();
                    System.out.println(Thread.currentThread().getName()+"解锁完成。");
                }
            }
        });
        t2.setName("通知线程");

        t1.start();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t2.start();
    }
}